package cn.tedu.ivos.dictoption.service.impl;

import ch.qos.logback.classic.Logger;
import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionSaveParam;
import cn.tedu.ivos.dictoption.pojo.entity.DictOption;
import cn.tedu.ivos.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivos.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DOServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper mapper;
    @Autowired
    DictMapper dmapper;
    @Override
    public List<DictOptionVO> selectDO(DictOptionQuery query) {
        List<DictOptionVO> list = mapper.select(query);
        return list;
    }

    @Override
    public void saveDictOption(DictOptionSaveParam dictOptionSaveParam) {
        DictOption dictOption = new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam, dictOption);
        if(dictOption.getId()==null){
            dictOption.setCreateTime(new Date());
            mapper.insert(dictOption);
        }else{
            dictOption.setUpdateTime(new Date());
            mapper.update(dictOption);
        }
    }

    @Override
    public void deleteOption(Long id) {
        mapper.delete(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByDictCode(String code) {
        log.debug("根据字典code查字典项业务,参数={}",code);
        DictQuery dictQuery = new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> dictVOList = dmapper.selectDict(dictQuery);
        if(dictVOList != null && dictVOList.size()>0){
            DictVO dictVO = dictVOList.get(0);
            DictOptionQuery dictOptionQuery = new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            List<DictOptionVO> dictOptionVOList =
                    mapper.selectDictOption(dictOptionQuery);
            return dictOptionVOList;
        }else{
            //如果查不到字典,说明字典code不存在
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }
}
